package meng.study.shiro.demo1;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {

	private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

	public static void main(String[] args) {

		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		SecurityManager securityManager = factory.getInstance();

		SecurityUtils.setSecurityManager(securityManager);

		// 获取当前用户
		Subject currentUser = SecurityUtils.getSubject();

		// 操作Session
		Session session = currentUser.getSession();
		session.setAttribute("myname", "mengzhang6");
		String value = (String) session.getAttribute("myname");
		if (value.equals("mengzhang6")) {
			log.info("session验证通过");
		}

		// let's login the current user so we can check against roles and
		// permissions:
		String username = "kafka";
		String password = "rocket";
		if (!currentUser.isAuthenticated()) {
			// 封装待验证对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			token.setRememberMe(true);
			try {
				// 认证
				currentUser.login(token);
			} catch (UnknownAccountException uae) {
				log.info("无此用户：{}", token.getPrincipal());
			} catch (IncorrectCredentialsException ice) {
				log.info("密码错误 ：{}", token.getPrincipal());
			} catch (LockedAccountException lae) {
				log.info("The account for username {} is locked.  " + "Please contact your administrator to unlock it.",
						token.getPrincipal());
				log.info("此用户被锁");
			}
			// ... catch more exceptions here (maybe custom ones specific to
			// your application?
			catch (AuthenticationException ae) {
				// unexpected condition? error?
			}
		}

		// print their identifying principal (in this case, a username):
		log.info("登录成功:{}", currentUser.getPrincipal());

		// 验证此用户是否为 xx角色
		if (currentUser.hasRole("admin")) {
			log.info("你是此角色，认证通过。");
		} else {
			log.info("认证失败。");
		}

		// 认证操作权限
		// schwartz = lightsaber:* --> 表示schwartz角色可以对lightsaber实体的任何实例做任何操作
		if (currentUser.isPermitted("lightsaber:weild")) {
			log.info("操作权限验证通过");
		} else {
			log.info("lightsaber:weild" + "操作权限验证失败");
		}

		// 认证操作权限 更细粒度的权限验证
		// goodguy = winnebago:drive:eagle5 -->
		// 表示goodguy角色可以对winnebago实体的eagle5实例 进行drive操作
		if (currentUser.isPermitted("winnebago:drive:eagle5")) {
			log.info("操作权限验证通过");
		} else {
			log.info("winnebago:drive:eagle5" + "操作权限验证失败");
		}

		// 登出
		currentUser.logout();

		System.exit(0);
	}
}
